package com.youlei.newgraduateproject.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.youlei.newgraduateproject.dao.SysUserMapper;
import com.youlei.newgraduateproject.entity.SysMenu;
import com.youlei.newgraduateproject.entity.SysRole;
import com.youlei.newgraduateproject.entity.SysUser;
import com.youlei.newgraduateproject.service.SysMenuService;
import com.youlei.newgraduateproject.service.SysRoleService;
import com.youlei.newgraduateproject.service.SysUserService;
import com.youlei.newgraduateproject.utils.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author youlei
 * @since 2021-05-08
 */
@Service
public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUser> implements SysUserService {

    @Autowired
    SysRoleService sysRoleService;

    @Autowired
    SysUserMapper sysUserMapper;

    @Autowired
    SysMenuService sysMenuService;

    @Autowired
    RedisUtil redisUtil;


    @Override
    public SysUser getByUserName(String username) {

        return getOne(new QueryWrapper<SysUser>().eq("username",username));
    }

    /**
     * @Author youlei
     * @Description 获取角色的权限信息
     * @Date 23:27 2021/5/11
     * @Param: [userId]
     * @return: java.lang.String
     **/
    @Override
    public String getUserAuthorityInfo(Long userId) {

        SysUser sysUser = sysUserMapper.selectById(userId);

        String authority="";
        //判断缓存中是否有权限数据
        if(redisUtil.hasKey("GrantedAuthority:"+sysUser.getUsername())){
            authority = (String) redisUtil.get("GrantedAuthority:" + sysUser.getUsername());
        }else {

            //获取角色,相当于select * from `sys_role` where id in(select role_id from sys_user_role where user_id =?)
            List<SysRole> roles = sysRoleService.list(new QueryWrapper<SysRole>()
                    .inSql("id", "select role_id from sys_user_role where user_id = " + userId));
            if(roles.size()>0){
                //将获取到的角色通过流式计算以逗号分隔开
                String roleCodes = roles.stream().map(r ->"ROLE_"+r.getCode()).collect(Collectors.joining(","));
                //不将.concat(",")放在下面是为了防止出现  ,sys:user:list,.....,逗号开头的情况
                authority =roleCodes.concat(",");
            }

            //获取菜单
            List<Long> menuIds = sysUserMapper.getNavMenuIds(userId);
            if(menuIds.size()>0){
                List<SysMenu> menus = sysMenuService.listByIds(menuIds);
                String menuPerms = menus.stream().map(m -> m.getPerms()).collect(Collectors.joining(","));
                authority = authority.concat(menuPerms);
            }
            //将权限数据存入Redis,存一天
            redisUtil.set("GrantedAuthority:"+sysUser.getUsername(),authority,60*60*24);

        }



        return authority;


    }

    @Override
    public void clearUserAuthorityInfoByUsername(String username) {
        redisUtil.del("GrantedAuthority:" + username);
    }

    @Override
    public void clearUserAuthorityInfoByRoleId(Long roleId) {
        List<SysUser> sysUsers = this.list(new QueryWrapper<SysUser>()
                .inSql("id", "select user_id from sys_user_role where role_id = " + roleId));

        sysUsers.forEach(u -> {
            this.clearUserAuthorityInfoByUsername(u.getUsername());
        });
    }

    @Override
    public void clearUserAuthorityInfoByMenuId(Long menuId) {
        List<SysUser> sysUsers = sysUserMapper.listByMenuId(menuId);

        sysUsers.forEach(u -> {
            this.clearUserAuthorityInfoByUsername(u.getUsername());
        });
    }


}
